package com.xn.app.muying.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.fragment.HomeFragment;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyApplication;
import com.xn.app.muying.util.StringUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.PickerView;
import com.zhuge.analysis.stat.ZhugeSDK;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 产检提醒页面
 * Created by gaoge on 2017/9/12.
 */

public class RemindActivity extends BaseActivity implements View.OnClickListener {

    //标题
    private TextView title = null;
    //返回键
    private ImageView img_back = null;
    //查看历史
    private ImageView img_right = null;
    //输入框
    private EditText edittext = null;
    //设置产检时间
    private RelativeLayout set_ymd = null;
    //设置提醒时间
    private RelativeLayout set_time = null;
    //显示产检时间
    private TextView time = null;
    //显示提醒时间
    private TextView remind_time = null;
    //加载框
    MyAlertDialog mydialog;
    //数据库对象
    private DBManager db = null;
    //本条产检的id
    private String id = null;
    //本条产检时间
    private String dateTime = null;
    //本条提醒时间
    private String remindTime = null;
    //本条产检备注
    private String content = null;
    //修改后的产检时间
    private String newDateTime = null;
    //修改后的提醒时间
    private String newRemindTime = null;
    //修改后的产检备注
    private String newContent = null;
    //获取数据
    private Intent intent = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.remind_activity);
        //初始化组件
        init();
    }

    /**
     * 初始化组件
     */
    private void init() {
        //初始化数据库对象
        db = new DBManager(this);
        //初始化组件
        title = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_right = (ImageView) findViewById(R.id.img_right);
        edittext = (EditText) findViewById(R.id.edittext);
        set_ymd = (RelativeLayout) findViewById(R.id.set_ymd);
        set_time = (RelativeLayout) findViewById(R.id.set_time);
        time = (TextView) findViewById(R.id.time);
        remind_time = (TextView) findViewById(R.id.remind_time);
        //显示按钮
        img_right.setImageResource(R.mipmap.history_img);
        img_right.setVisibility(View.VISIBLE);
        //设置标题
        title.setText("产检提醒");
        //添加点击事件
        img_back.setOnClickListener(this);
        img_right.setOnClickListener(this);
        set_time.setOnClickListener(this);
        set_ymd.setOnClickListener(this);
        //获取数据
        intent = getIntent();
        id = intent.getStringExtra("id");
        dateTime = intent.getStringExtra("antenatalCareTime");
        remindTime = intent.getStringExtra("remindTime");
        content = intent.getStringExtra("remark");
        //设置内容
        if (StringUtil.judgeNull(id)) {
            //设置产检时间
            if (StringUtil.judgeNull(dateTime)) {
                dateTime=dateTime.split("T")[0];
                time.setText(dateTime);
            }
            //设置提醒时间
            if (StringUtil.judgeNull(remindTime)) {
                String str=remindTime.split("T")[0];
                remindTime= remindTime.split("T")[1];
                if (dateTime.split("T")[0].equals(str)) {
                    remindTime = "当天" + remindTime.split(":")[0] + "时" + remindTime.split(":")[1] + "分";
                } else {
                    remindTime = "前一天" + remindTime.split(":")[0] + "时" + remindTime.split(":")[1] + "分";
                }
                remind_time.setText(remindTime);
            }
            //设置提醒备注
            if (StringUtil.judgeNull(content)) {
                edittext.setText(content);
                edittext.setSelection(edittext.getText().length());
            }
        }
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回键
            case R.id.img_back:
                saveDate();
                break;
            //查看历史
            case R.id.img_right:
                startActivity(new Intent(this,RemindHistoryActivity.class));
                break;
            //设置产检时间
            case R.id.set_ymd:
                //加载弹出框
                mydialog = new MyAlertDialog();
                mydialog.SetTime_Dialog(this, R.layout.time_dialog);
                final PickerView date_picker1 = mydialog.getDate_picker1();
                final PickerView date_picker2 = mydialog.getDate_picker2();
                final PickerView date_picker3 = mydialog.getDate_picker3();
                final TextView text1 = mydialog.getText1();
                final TextView text2 = mydialog.getText2();
                final TextView text3 = mydialog.getText3();
                //设置时间控件
                new DateUtils().setTimeyMd(date_picker1, date_picker2, date_picker3, text1, text2, text3);
                //设置取消按钮
                TextView getCancel_text = mydialog.getCancel_text();
                getCancel_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mydialog != null) {
                            mydialog.dismiss();
                        }
                    }
                });
                //设置确定按钮
                TextView getConfirm_text = mydialog.getConfirm_text();
                getConfirm_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mydialog != null) {
                            mydialog.dismiss();
                        }
                        //设置时间
                        time.setText(date_picker1.getData() + "-" + date_picker2.getData() + "-" + date_picker3.getData());
                    }
                });
                break;
            //设置提醒时间
            case R.id.set_time:
                //加载弹出框
                mydialog = new MyAlertDialog();
                mydialog.SetTime_Dialog(this, R.layout.time_dialog);
                final PickerView time_picker1 = mydialog.getDate_picker1();
                final PickerView time_picker2 = mydialog.getDate_picker2();
                final PickerView time_picker3 = mydialog.getDate_picker3();
                final TextView time_text1 = mydialog.getText1();
                final TextView time_text2 = mydialog.getText2();
                final TextView time_text3 = mydialog.getText3();
                //设置时间控件
                DateUtils.setTimeHms(time_picker1, time_picker2, time_picker3, time_text1, time_text2, time_text3);
                //设置取消按钮
                TextView getTimeCancel_text = mydialog.getCancel_text();
                getTimeCancel_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mydialog != null) {
                            mydialog.dismiss();
                        }
                    }
                });
                //设置确定按钮
                TextView getTimeConfirm_text = mydialog.getConfirm_text();
                getTimeConfirm_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (mydialog != null) {
                            mydialog.dismiss();
                        }
                        remind_time.setText(time_picker1.getData() + time_picker2.getData() + "时" + time_picker3.getData() + "分");
                    }
                });
                break;
        }
    }

    /**
     * 保存用户设置的提醒时间，并且退出当前页面
     */

    public void saveDate() {
        newDateTime = time.getText().toString();
        newRemindTime = remind_time.getText().toString();
        newContent = edittext.getText().toString();
        if (dateTime.equals(newDateTime) && remindTime.equals(newRemindTime) && content.equals(newContent)) {
            finish();
        } else {
            if (StringUtil.judgeNull(newDateTime) || StringUtil.judgeNull(newRemindTime) || StringUtil.judgeNull(newContent)) {
                //加载弹出框
                mydialog = new MyAlertDialog();
                mydialog.Temperature_Dialog(this, R.layout.remind_save_dialog);
                TextView data = mydialog.getData();
                TextView getConfirm_text = mydialog.getConfirm_text();
                TextView getCancel_text = mydialog.getCancel_text();
                //设置内容
                data.setText("是否保存本次设置的产检提醒信息?");
                //设置取消按钮
                getCancel_text.setText("不保存");
                getCancel_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mydialog.dismiss();
                        finish();
                    }
                });
                //设置确认按钮
                getConfirm_text.setText("保存");
                getConfirm_text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mydialog.dismiss();
                        if (StringUtil.judgeNull(newDateTime)) {
                            if (StringUtil.judgeNull(newRemindTime)) {
                                if (newRemindTime.contains("前一天")) {
                                    newRemindTime = DateUtils.getYesterday(newDateTime) + newRemindTime.replace("前一天", " ").replace("时", ":").replace("分", ":00");
                                } else {
                                    newRemindTime = newDateTime + newRemindTime.replace("当天", " ").replace("时", ":").replace("分", ":00");
                                }
                                //判断提醒时间是否过期
                                if (DateUtils.getStringToDate(newRemindTime) > DateUtils.getNumberDate()) {
                                    if (StringUtil.judgeNull(newContent)) {
                                        if (newContent.length() < 2 || newContent.length() > 60) {
                                            ToastUtil.showToast(RemindActivity.this, "备注字数不符合规定");
                                        } else {
                                            //提交数据
                                            submitRemind(newDateTime, newRemindTime, newContent);
                                        }
                                    } else {
                                        //提交数据
                                        submitRemind(newDateTime, newRemindTime, newContent);
                                    }
                                } else {
                                    //提醒时间过期
                                    ToastUtil.showToast(RemindActivity.this, "提醒时间不能设置为已过期的时间");
                                }
                            } else {
                                ToastUtil.showToast(RemindActivity.this, "提醒时间不能为空");
                            }
                        } else {
                            ToastUtil.showToast(RemindActivity.this, "产检日期不能为空");
                        }

                    }
                });
            } else {
                finish();
            }
        }
    }

    /**
     * 向服务器提交设置的产检提醒
     *
     * @param newDateTime   产检时间
     * @param newRemindTime 提醒时间
     * @param newContent    提醒内容
     */
    private void submitRemind(final String newDateTime, final String newRemindTime, final String newContent) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final HashMap<String, Object> param = new HashMap<>();
                    if (StringUtil.judgeNull(AppConstant.remindId) && !AppConstant.remindId.equals("0")) {
                        param.put("id", AppConstant.remindId);
                    }
                    param.put("remindTime", newRemindTime);
                    param.put("antenatalCareTime", newDateTime);
                    param.put("remark", newContent);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.setRemind).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).post(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    final int code = response.code();
                    String bodys = response.body().string();

                    Log.e("","");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (code == 200 || code == 204) {
                                ToastUtil.showToast(RemindActivity.this, "产检提醒设置成功");
                                //通知页面更新
                                sendBroadcast(new Intent("bei_er").putExtra("bei_er", 0));
                                finish();
                            } else {
                                ToastUtil.showToast(RemindActivity.this, "设置产检提醒失败，请重新设置");
                            }
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            saveDate();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
